/**
 * UVa 548 Tree (AC)
 * Author: chchwy (a) gmail.com
 * Last modified: 2010.04.22
 */
#include<iostream>
#include<sstream>
#include<vector>
using namespace std;

class node{
public:
    int value; //the value of this node
    int sum;   //the sum of path from root to current node
    node *lc, *rc;
    node(){ value=0, sum=0; }
    node(int v,int s){value=v,sum=s;};
};

node* External = new node(0,INT_MAX);

//parse strings to a integer vector
void parseIntLine(vector<int> &list, string &line){

    stringstream sin(line);
    int n;
    while(sin>>n)
        list.push_back(n);
}

/* build a tree by inorder and postorder sequence */
node* buildTree( vector<int>::iterator begin,
                 vector<int>::iterator end,
                 vector<int> &postorder){

    if(postorder.empty())
        return External;

    vector<int>::iterator it = find(begin, end, postorder.back());
    if( it==end ) //not found
        return External;

    int value = postorder.back(); postorder.pop_back();

    node* root = new node();
    root->value = value;
    root->rc = buildTree(it+1, end, postorder);
    root->lc = buildTree(begin, it, postorder);

    return root;
}

node* do_summing(node* cur, int path_sum){

    if(cur==External) return External;

    //往下累加path sum
    cur->sum = cur->value + path_sum;

    node *lc = do_summing(cur->lc, cur->sum);
    node *rc = do_summing(cur->rc, cur->sum);

    if(lc==External && rc==External) //leaf node
        return cur;

    //回傳最小的leaf node
    return (lc->sum < rc->sum)? lc : rc;
}

int main(){
    #ifndef ONLINE_JUDGE
    freopen("548.in","r",stdin);
    #endif

    string line1, line2;
    while( getline(cin,line1) && getline(cin,line2) ){

        vector<int> inorder, postorder;

        parseIntLine(inorder, line1);
        parseIntLine(postorder,line2);

        node* root = buildTree(inorder.begin(),inorder.end() ,postorder);

        printf("%d\n", dfs(root,0)->value );
    }
    return 0;
}
